/**
 * 医德档案模块，提供医德档案查看业务功能
 * 
 * @Date: 2016-1-21
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(
		[ "jquery", "datagridServ", "sysmanMain", "bizProto", "btnServ","ethicUtil",
				"msgServ", "flowInit", "buttonEvent", "deptUserSelect" ],
		function($, datagridServ, sysmanMain, bizProto, btnServ,ethicUtil, msgServ,
				flowInit, buttonEvent, deptUserSelect) {

			'use strict';

			var _typeUrl = '/dictionary/getTree.action', _rootpath,
			// 评分详情url
			_initScoreListUrl = '/ethicEvaluate/query/getSubListDomainByMainId.action',
			// 编辑url
			_editUrl = '/ethicEvaluate/query/mainEditPage.action',

			_addScoreUrl = '/ethicEvaluate/query/getAddMinScore.action',
			// 评价列表url
			_evaluateUrlPre = '/ethicEvaluate/query', item_code_dic_id = 32, 
			
			
			//dom根节点id
			rootId = 'panel-ethic-archive',
			// rootId = 'panel-self-ethic-evaluation',
			// rootId = 'panel-ethic-evaluation',
			edit_window_id = 'ethic-archive-win', editIndex = -1,

			editIndex1 = -1, editBegin = false, el_width = 300, el_big_width = 674, window_width = 900, window_height = 600, $activityListGrid,
			// 当前列表点击行号
			currentListIndex = -1,

			// 考评类型定义 
			evaluate_code = {
				person : 'person',
				person_code : 0,

				dept : 'dept',
				dept_code : 1,

				party : 'party',
				party_code : 2,

				all : 'all',
				all_code : 3,

				finish : 'finish',
				finish_code : 4,

				lock_code : 5
			},
			// 考评类型
			evaluate_type = evaluate_code.person,
			// 双击列表传递参数值
			_data,

			// 设置评价分类类别（按科室评价、全院评价、资料归档分类）
			classify_type,
			// 根据不同的分类，以便获得不同的属性
			tempcolumns,
			// 标记变量，让部门列表树初始化一次就不再初始化
			deptInitializd,		
				
			bizcode = ''
			
			
			var public_method = {

				initRootId : function() {
					rootId = sysmanMain.getCurrentModuConfig().rootId;
				},

				/**
				 * 提交后执行
				 */
				afterSubmit : function(_options) {
					private_method.afterSubmit();
				},
				/**
				 * 提交前补充字表数据
				 */
				beforeSubmit : function(_options) {
					return private_method.beforeSubmit(_options)
				},
				/**
				 * 编辑页面初始化
				 */
				initEdit : function(_options) {
					private_method.initEdit(_options)
				},
				/**
				 * 初始化新增页面
				 * 
				 * @param _options.record
				 *            列表选中行
				 * @param _options.form
				 *            页面form对象
				 */
				initList : function(_options) {
					private_method.initList();
				},

				/**
				 * @param _options.record
				 */

				closeWindow : function() {
					$('#' + edit_window_id).empty()
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					_moduleConfig.initParam = {
						editable : true
					};
					sysmanMain.setCurrentModuConfig(_moduleConfig);
				},

				reCreateField : function(_options) {
					private_method.reCreateField(_options)
				},
				rowDblClick : function(index, row) {
					private_method.rowDblClick(index, row)
				},
				buttonExtends : function(_options) {
					return {
						'自动院评' : function() {
							private_method.autoScore()
						},
						'提交院评' : function() {
							private_method.auditOne()
						},
						'批量提交' : function() {
							private_method.auditList()
						},
						'保存院评' : function() {
							private_method.save()
						},
						'查看' : function() {
							private_method.showDetail(_options)
						},
						'清除选择':function(){
							var _grid = $('#'+rootIds.finishRootId + ' .dg-list')
							if(_grid.length==1){
								_grid.datagrid('clearSelections');
							}
						}
					}
				}

			}

			var private_method = {	
				// 获取加扣分详情
				initAddMinScoreList : function() {
					// 获取当前用户和考评期
					var _data = {
						uid : $('#' + edit_window_id + ' #person_code').val(),
						eval_year : $('#' + edit_window_id + ' #evaluate_year')
								.val()
					}

					var _url = '/ethicEvaluate/query/getAddMinScoreDetail.action';
					if (_data.uid && _data.eval_year) {
						_url += ("?uid=" + _data.uid + "&eval_year=" + _data.eval_year)
					}
					// html 中对应的div
					var _gridid = edit_window_id + ' div.evaluate-add-detail'
					var _grid = $('#' + _gridid)
					if (_grid.length == 1) {
						var _gridParam = {
							url : '/' + sysmanMain.getRootPath() + _url,
							idField : 'id',
							fitColumns : true,
							onLoadSuccess : function(data) {
								if (data && data.rows.length > 0) {
									datagridServ.mergeCellsByField({
										tableID : _gridid,
										colList : 'addorminus_type'
									})
								}
							},
							onClickCell : private_method.editCell,
							columns : [ [ {
								field : 'addorminus_type',
								title : '分数类别',
								align : 'center',
								width : 20
							}, {
								field : 'item_name',
								title : '加扣分内容',
								width : 180,
								align : 'center'
							}, {
								field : 'score',
								title : '分数值',
								width : 20,
								align : 'center'
							} ] ]
						}
						$(_grid).datagrid(_gridParam)
					}

				},

				// 查看按钮
				showDetail : function(_options) {
					var _config = sysmanMain.getCurrentModuConfig();
					if (_config && _config.rootId) {
						var $grid = $('#' + _config.rootId + " table.dg-list");
						var $edit_window = $('#' + _config.editWindow);
						var _bizProto = _config.bizProto

						var _url
						if (_config.editPageUrl) {
							_url = _config.editPageUrl({
								record : $($grid).datagrid('getSelected')
							})
						} else {
							_url = _bizProto.flowEidtPageUrl
						}

						var _param = {
							grid : $grid,
							window : $edit_window,
							href : _url,
							width : _config.edit_window_width,
							height : _config.edit_window_height,
							flag : true,
							existCheckElement : 'form'
						}

						if (_config.onWindowClose) {
							_param.onClose = _config.onWindowClose
						}
						datagridServ.windowEdit(_param);
					}
					private_method.initEdit(_options);
				},

				// 显示总分数和考评日期
				showTotScoreAndDate : function(data) {
					if (data) {
						var tot_score = 0;
						for (var i = 0; i < data.rows.length; i++) {
							tot_score += data.rows[i].sub_score;
						}
						var current_date = new Date();
						$('#' + edit_window_id + ' #tot_score').textbox(
								'setValue', tot_score);
					}
				},

				save : function() {

					$($activityListGrid).datagrid('acceptChanges');
					var _data = $($activityListGrid).datagrid('getData')

					if (_data && _data.rows) {
						// save data to remote

						var _url = '/' + sysmanMain.getRootPath()
								+ '/ethicEvaluate/saveList.action'
						$.ajax({
							url : _url,
							type : 'post',
							dataType : 'json',
							data : $.toJSON(_data.rows),
							contentType : 'appliction/json;charset=utf-8',
							success : function(data) {
								msgServ.Msgslide('操作成功');
							}
						})
					}
				},

				// 列表页面初始化
				initList : function() {
					//获取rootId
					public_method.initRootId();
					deptInitializd = false;
					private_method.typeClick({
						type : evaluate_code.all
					});
				},
				/**
				 * 评价类型监听事件
				 * 
				 * @param _options.type
				 *            评价类型
				 */
				typeClick : function(_options) {
					evaluate_type = _options.type
					private_method.initListGridRow(_options)
				},
				/**
				 * 初始化列表字段
				 * 
				 * @param _options.type
				 *            评价类型
				 */
				initListGridRow : function(_options) {

					var _gridParam = {
						rownumbers : true,
						animate : true,
						striped : true,
						border : true,
						idField : 'id',
						fitColumns : true,
						checkOnSelect : true,
						pagination : true,
						selectOnCheck : true,
						onClickCell : private_method.editCells,
						rowStyler: function(index,row){
							if(row && !(row.status==3) ){
								return 'background-color:#efefef;color:#666;'; 
							}
						}
					}
					var _columns = [ {
						field : 'ck',
						checkbox : true
					}, {
						field : 'person_name', 
						title : '人员姓名',
						width : 30,
						align : 'center'
					}, {
						field : 'evaluate_year',
						title : '考评年度',
						width : 60,
						align : 'center'
					}, {
						field : 'daily_evaluate',
						title : '日常考评',
						width : 60,
						align : 'center',
						formatter : function (value, row, index) {
							return row.daily_evaluate
						}
					}, {
						field : 'gift_return',
						title : '红包礼品退还',
						width : 60,
						align : 'center',
						formatter : function (value, row, index) {
							return row.gift_return
						}
					}, {
						field : 'depart_name',
						title : '所在科室',
						width : 50,
						align : 'center'
					}, {
						field : 'sel_score',
						title : '自评得分',
						width : 30,
						align : 'center'
					}, {
						field : 'dept_score',
						title : '科室评分',
						width : 30,
						align : 'center'
					}, {
						field : 'composite_score',
						title : '医院评分',
						width : 30,
						align : 'center',
						editor : 'text'
					}, {
						field : 'show_score',
						title : '评价等级',
						width : 40,
						align : 'center',
						formatter : function(value, row, index) {
							if (row.composite_score >= 95) {
								return "优秀";
							} else if (row.composite_score >= 85) {
								return "良好";
							} else if (row.composite_score >= 65) {
								return "一般";
							} else if (row.composite_score >= 0) {
								return "差";
							} else {
								return "差";
							}
						}
					}]

					if (_options.type) {
						private_method.initDeptUser(_options.type);
					}
					var _url = '/' + sysmanMain.getRootPath() + '/recordEthicEvaluate/query'
							+ '/getAllListDomain.action';
					_gridParam.url = _url
					_gridParam = $.extend({}, _gridParam, {
						columns : [ _columns ]
					})
					tempcolumns = _columns;
					var _listGrid = $('#' + rootId + ' table.dg-list')
					$activityListGrid = $(_listGrid).datagrid(_gridParam)

				},

				/**
				 * 初始化部门
				 * 
				 * @param _options.bizProto
				 */
				initDeptUser : function(type) {
					var $dept = $('#' + rootId + ' div.tg-department');

					classify_type = type

					var deptTreeUrl = "/honest/department/query/getTreeList.action";
					// 部门信息
					if ($dept && $dept.length > 0) {
						if (!deptInitializd) {
							$dept
									.treegrid({
										rownumbers : true,
										animate : true,
										idField : 'id',
										treeField : 'name',
										striped : true,
										border : true,
										fitColumns : true,
										height : window_height,
										width : el_width,
										url : deptTreeUrl,
										onClickRow : private_method.getClassifyValuation,
										columns : [ [ {
											field : 'name',
											title : '部门名称',
											width : 60,
											halign : 'center'
										} ] ]
									})
						}
					}
					deptInitializd = true;
				},

				/**
				 * 按照条件（部门）分别获取医德评价信息
				 */
				getClassifyValuation : function(row) {
					var _url = '/getAllListDomain.action'
					var _gridParam = {
						rownumbers : true,
						animate : true,
						striped : true,
						border : true,
						// singleSelect:false,
						idField : 'id',
						fitColumns : true,
						checkOnSelect : true,
						pagination : true,
						selectOnCheck : true,
						onClickCell : private_method.editCells
					};
					_gridParam.url = '/' + sysmanMain.getRootPath()
							+ '/recordEthicEvaluate/query' + _url;
					_gridParam.queryParams = {
						condition : {
							depart_code : row.id
						}
					}

					_gridParam = $.extend({}, _gridParam, {
						columns : [ tempcolumns ]
					})

					var _listGrid = $('#' + rootId + ' table.dg-list')
					$activityListGrid = $(_listGrid).datagrid(_gridParam)

				},

				// 编辑页面初始化
				initEdit : function(_options) {
					// 评价人员姓名及科室
					if (_data) {
						$('#' + edit_window_id + ' form.main-form').form(
								'load', _data)
						_data = null
					}
					// 初始化评分表
					private_method.initScoreList();
					// 初始化加扣分详情
					private_method.initAddMinScoreList();
				},

				afterSubmit : function() {
					$('#' + rootId + ' table.dg-list').datagrid('reload')
					private_method.initScoreList();

				},
				// 初始化评分表
				initScoreList : function() {
					if (window.console) {
						console.log('initScoreList loaded and starting... ')
					}
					var _url
					var _idVal = $('#' + edit_window_id + ' #lobid').val()
					if (!_idVal || _idVal == '') {
						_url = _initScoreListUrl;
					} else {
						_url = _initScoreListUrl + '?lobid=' + _idVal
					}

					var _gridid = edit_window_id + ' div.evaluate-sub'
					var _grid = $('#' + _gridid)
					if (_grid.length == 1) {
						var _gridParam = {
							url : '/' + sysmanMain.getRootPath() + _url,
							striped : true,
							border : true,
							nowrap : false,
							// singleSelect:false,
							idField : 'id',
							fitColumns : true,
							onLoadSuccess : function(data) {
								if (data && data.rows.length > 0) {
									datagridServ.mergeCellsByField({
										tableID : _gridid,
										colList : 'item_name'
									})
									private_method.showTotScoreAndDate(data);
								}
							},

							onClickCell : private_method.editCell,
							columns : [ [
							// {field:'ck',checkbox:"true"},
							{
								field : 'item_name',
								title : '项目类别',
								align : 'center',
								width : 80
							}, {
								field : 'sub_content',
								title : '考评内容',
								width : 120,
								align : 'center'
							}, {
								field : 'sub_score',
								title : '单项分值',
								width : 20,
								align : 'center'
							}, {
								field : 'sel_score',
								title : '自评得分',
								width : 20,
								align : 'center'
							}, {
								field : 'evaluate_result',
								title : '考评情况',
								width : 60,
								align : 'center'
							} ] ],
							onAfterEdit : function(index, row, changes) {
								private_method.afterEdit(index, row, changes)
							},
							onEndEdit : function(index, row, changes) {
								private_method.afterEdit(index, row, changes)
							}

						}
						$(_grid).datagrid(_gridParam)
					}
				},
				rowDblClick : function(index, row) {

					var editWindow = edit_window_id;
					var _param = {}
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					if (!_moduleConfig) {
						_moduleConfig = {}
					}

					var _param = {
						index : index,
						row : row,
						rootId : rootId,
						editWindow : edit_window_id,
						// moduleConfig:sysmanMain.getCurrentModuConfig(),传入空值，自动取当前模块配置
						url : _editUrl,
						maxWindowSize : true,
						width : window_width,
						height : window_height
					}
					// 暂存选中行
					_data = row

					// 设定当前选中行
					currentListIndex = index
					buttonEvent.doubleClickEdit(_param)

				},
				beforeSubmit : function(_options) {
					var _gridid = edit_window_id + ' div.evaluate-sub'
					if (editBegin) {
						$('#' + _gridid).datagrid('acceptChanges');
						$('#' + _gridid).datagrid('endEdit', editIndex);
						editIndex = -1;
					}
					var _data = $('#' + _gridid).datagrid('getData')

					/**
					 * 未进入编辑状态，强行触发分数统计
					 */
					if (!editBegin) {
						private_method.afterEdit()
					}
					if (_data && _data.rows) {
						return {
							sublist : $.toJSON(_data.rows)
						}
					}
				},
				editCell : function(index, field, value) {
					if (window.console)
						console.info(' editCell fired ...')
					var _gridid = edit_window_id + ' div.evaluate-sub'

					if (field == 'sel_score' || field == 'evaluate_result'
							|| field == 'dept_score') {
						if (!editBegin) {
							editBegin = true
						}
						$('#' + _gridid).datagrid('beginEdit', index);

						if (editIndex > -1 && (editIndex != index)) {
							editIndex = index
						}

					}
				},

				editCells : function(index, field, value) {
					$activityListGrid = $('#' + rootId + ' table.dg-list')
					if (window.console)
						console.info(' editCells fired ...')
					if (field == 'dept_score' || field == 'dept_evaluate'
							|| field == 'composite_score'
							|| field == 'hospital_evaluate') {
						if (editIndex1 > -1 && (editIndex1 != index)) {
							$($activityListGrid).datagrid('acceptChanges');
							$($activityListGrid)
									.datagrid('endEdit', editIndex1);
						}

						$($activityListGrid).datagrid('beginEdit', index);
						editIndex1 = index

					}
				},

				afterEdit : function(index, row, changes) {
					if (window.console) {
						console.log('afterEdit fired ...')
					}
					var _grid = $('#' + edit_window_id + ' div.evaluate-sub')
					var countScore = 0.0

					if (_grid.length == 1) {
						var _data = $(_grid).datagrid('getData')
						if (_data && _data.rows) {
							$.each(_data.rows, function(i, row) {
								if (row.sel_score)
									countScore += parseFloat(row.sel_score)
							})
						}
					}

					private_method.setCountScore(countScore)

				},
				/**
				 * 自动评分
				 * 
				 */
				autoScore : function() {
					var target_grid, sourceField, targetField
					switch (evaluate_type) {
					case evaluate_code.person:
						target_grid = $('#' + edit_window_id
								+ ' div.evaluate-sub')
						sourceField = 'sub_score';
						targetField = 'sel_score';
						break;
					case evaluate_code.dept:
						target_grid = $('#' + rootId + ' table.dg-list')
						sourceField = 'sel_score';
						targetField = 'dept_score';
						break;
					case evaluate_code.all:
						target_grid = $('#' + rootId + ' table.dg-list')
						sourceField = 'dept_score';
						targetField = 'composite_score';
						break;
					// case evaluate_code.finish:
					// target_grid = $('#'+rootId +' table.dg-list')
					// sourceField = 'composite_score';
					// targetField = 'show_score';

					break;
				default:
					target_grid = $('#' + edit_window_id + ' div.evaluate-sub')
					sourceField = 'sub_score';
					targetField = 'sel_score';

				}
				if (target_grid && target_grid.length == 1) {

					var _grid = target_grid
					// 合计分数
					var countScore = 0.0
					var _records = $(target_grid).datagrid('getRows')

					$.each(_records, function(i, record) {
						if (record[sourceField]) {
							record[targetField] = record[sourceField]
							countScore += parseFloat(record[sourceField]);
						}
					})

					$(target_grid).datagrid('loadData', _records)
					private_method.setCountScore(countScore)
				}
			},
				setCountScore : function(val) {
					var _countEl = $('#' + edit_window_id + ' #sel_score')
					if (_countEl.length == 1) {
						$(_countEl).textbox('setValue', val.toFixed(1))
					}
				},

				auditOne : function() {
					var _auditVal = 0, target_grid

					// 根据考评类型生成状态标志
					switch (evaluate_type) {
					case evaluate_code.person:
						target_grid = $('#' + edit_window_id
								+ ' div.evaluate-sub');
						_auditVal = evaluate_code.dept_code
						break;
					case evaluate_code.dept:
						target_grid = $('#' + rootId + ' table.dg-list');
						_auditVal = evaluate_code.all_code
						break;
					case evaluate_code.all:
						target_grid = $('#' + rootId + ' table.dg-list')
						_auditVal = evaluate_code.finish_code
						break;
					case evaluate_code.finish:
						target_grid = $('#' + rootId + ' table.dg-list')
						_auditVal = evaluate_code.lock_code
						break;
					default:
						target_grid = $('#' + edit_window_id
								+ ' div.evaluate-sub');
						_auditVal = 1
					}

					var _id = $('#' + edit_window_id + ' #id')
					var _idVal
					if (_id.length == 1) {

						_idVal = $(_id).val()
						// id为空
						if (!_idVal || _idVal == '') {
							msgServ('请先保存考评记录')
							return

						}
					}

					var _auditUrl = '/' + sysmanMain.getRootPath()
							+ '/ethicEvaluate/auditOne.action'

					$.messager.confirm('警告', '提交后将无法修改考评内容，确定执行操作?',
							function(r) {

								if (r) {
									var _data = {
										id : _idVal,
										status : _auditVal
									}
									var _param = {
										url : _auditUrl,
										data : _data,
										success : function(data) {
											msgServ.Msgslide('提交操作成功');

											$(target_grid).datagrid(
													'clearSelections')
											$(target_grid).datagrid('load')
											$('#' + edit_window_id).window(
													'close')

										},
										error : function() {
											msgServ.Msgslide('提交操作失败');
										}
									}
									$.ajax(_param)
								}
							})

				},
				/**
				 * 批量提交考评记录
				 */
				auditList : function() {
					//dom根节点
					var tempRootId = sysmanMain.getCurrentModuConfig().rootId;	
					
					// 保存修改
					var target_grid = $('#' + tempRootId + ' .dg-list');
					if (editBegin) {
						$(target_grid).datagrid('acceptChanges');
						$(target_grid).datagrid('endEdit', editIndex);
						editIndex = -1;
					}
									
					
					//下一节点状态值					
					var _auditVal = rootIds.finishCode;
					
					//当前节点状态值
					var _curStatus = 3
					
					//调用批量提交考评记录方法
					ethicUtil.auditList({
						rootId:tempRootId,
						auditVal:_auditVal,
						valStandard:_curStatus
					})
				}
			}

			return public_method;

		});